package com.glsc.ngateway.platform.service.cmdb;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.enums.DictConstant;
import com.glsc.ngateway.common.base.domain.mysql.cmdb.CmdbChangeLog;
import com.glsc.ngateway.common.base.domain.mysql.cmdb.CmdbMachineCabinet;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.cmdb.CmdbChangeLogRepository;
import com.glsc.ngateway.common.base.repo.mysql.cmdb.CmdbMachineCabinetRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

import static com.glsc.ngateway.common.api.common.enums.DictConstant.*;

@Service
public class CmdbMachineCabinetService {

    @Autowired
    private SequenceProductService sequenceProductService;
    @Autowired
    private CmdbMachineCabinetRepository cmdbMachineCabinetRepository;
    @Autowired
    private CmdbChangeLogRepository cmdbChangeLogRepository;

    public Object search(String type, Object paramsObj) {
        JSONObject objParmams = JSONObject.parseObject(JSONObject.toJSONString(paramsObj)).entrySet().stream()
                .filter(entry -> !entry.getValue().toString().isEmpty())
                .collect(JSONObject::new, (obj, entry) -> obj.put(entry.getKey(), entry.getValue()), JSONObject::putAll);

        if (StrUtil.isEmpty(objParmams.getString("orderByDirection"))){
            objParmams.put("orderByDirection","DESC");
        }
        if (StrUtil.isEmpty(objParmams.getString("orderByField"))){
            objParmams.put("orderByField","id");
        }
        Sort sort = Sort.by(Sort.Direction.fromString(objParmams.getString("orderByDirection")), objParmams.getString("orderByField"));

        Pageable pageable = PageRequest.of(objParmams.getInteger("pageNo")- 1, objParmams.getInteger("pageSize"),sort);

        if (CMDB_MACHINE_CABINET.equals(type)){
            CmdbMachineCabinet paramSearchDto = JSONObject.parseObject(JSONObject.toJSONString(objParmams),CmdbMachineCabinet.class);
            Page<CmdbMachineCabinet> result = cmdbMachineCabinetRepository.searchByParam(pageable,paramSearchDto);
            return  result;
        }


        return null;
    }

    /**
     *
     * @param cmdbMachineCabinet
     * @param account  操作人员
     */
    public void addOrUpdateMachineCabinet(CmdbMachineCabinet cmdbMachineCabinet, String account) {
        int addOrUpdateFlag = 0;
        cmdbMachineCabinet.setIsDelete(NO_DELETE);
        CmdbChangeLog log = new CmdbChangeLog();
        if (cmdbMachineCabinet.getId() != null){
            //修改
            log.setChangeType(DictConstant.UPDATE_STRING);
            addOrUpdateFlag = 2;
        } else {
            //新增
            log.setChangeType(DictConstant.ADD_STRING);
            //自动生成编号
            String code = sequenceProductService.buildSequence(CMDB_MACHINE_CABINET);
            cmdbMachineCabinet.setMachineCabinetCode(code);
            addOrUpdateFlag = 1;
        }
        log.setChangeContent(JSONObject.toJSONString(cmdbMachineCabinet));
        log.setChangeFrom(CMDB_MACHINE_CABINET);
        log.setChangeId(cmdbMachineCabinet.getId() != null ? cmdbMachineCabinet.getId().toString() : null);
        log.setChangeUser(account);
        cmdbChangeLogRepository.save(log);
        cmdbMachineCabinetRepository.save(cmdbMachineCabinet);
    }

    public void deleteMachineCabinet(CmdbMachineCabinet cmdbMachineCabinet, String account) {
        CmdbChangeLog log = new CmdbChangeLog();
        log.setChangeContent(JSONObject.toJSONString(cmdbMachineCabinet));
        log.setChangeFrom(CMDB_MACHINE_CABINET);
        log.setChangeId(cmdbMachineCabinet.getId().toString());
        log.setChangeUser(account);
        log.setChangeType(DELETE_STRING);
        Optional<CmdbMachineCabinet> optional = cmdbMachineCabinetRepository.findById(cmdbMachineCabinet.getId().intValue());
        if (optional.isPresent()) {
            CmdbMachineCabinet bean = optional.get();
            bean.setIsDelete(DELETED);
            cmdbMachineCabinetRepository.save(bean);
            cmdbChangeLogRepository.save(log);
        } else {
            throw PlatformException.errorWithOutMail("删除记录不存在");
        }
    }

    public void deleteByCodeList(List<String> codes, String account) {
        CmdbChangeLog log = new CmdbChangeLog();
        log.setChangeContent(JSONObject.toJSONString(codes));
        log.setChangeFrom(CMDB_MACHINE_CABINET);
        log.setChangeUser(account);
        log.setChangeType(DELETE_BATCH_STRING);
        cmdbChangeLogRepository.save(log);
        cmdbMachineCabinetRepository.updateIsDeleteByCodes(DELETED,codes);

    }
}
